<template>
  <el-dialog
    :close-on-click-modal="false"
    title="入库"
    :visible.sync="dialogTablesVisible"
    :modal-append-to-body="false"
    id="equmentBatch">
    <template>
      <el-tabs type="card" id="tabCard" >
        <div>
          <el-steps :active="disc_current" simple finish-status="success">
            <el-step title="选择入库设备"></el-step>
            <el-step title="选择库位"></el-step>
            <el-step title="入库完成"></el-step>
          </el-steps>
          <!-- 第一步分开分配 -->
          <el-row id="firstCard" v-if="disc_current === 1">
            <div class="firststorage">
              <el-form :model="set" @submit.native.prevent>
                <el-input
                  v-model="set.box_number"
                  @keyup.13.native="enterBox(set.box_number)"
                  placeholder="请通过扫码枪或手动添加获取箱号"
                  ref="inputsbox"
                ></el-input>
              </el-form>
              <el-button type="primary" slot="append" @click="enterBox(set.box_number)"  :loading="isBoxLoading">
                  <span v-if="!isBoxLoading">添加</span>
                  <span v-if="isBoxLoading">添加中</span>
              </el-button>
            </div>
            <div v-if="show_one" style="margin: 97px auto 0px;text-align: center;">
              <img src="/static/image/device/b-yellow.png">
            </div>
            <vue-scroll :ops="ops" v-show="!show_one">
              <div style="padding:0px;margin-top: 30px;width: 100%;">
                <div
                  v-for="item in arrbox"
                  :key="item.key"
                  style="float: left;width: 280px;height: 50px;margin: 0 7px 15px 7px;box-shadow: 0px 4px 18px rgba(69, 71, 74, 0.1);background: #fff;line-height: 50px;font-size:18px; font-weight:bold;"
                >
                  <img
                    src="/static/image/device/shebei-1.png"
                    style="float:left;margin:8px 5px 0px 12px;"
                  >
                  {{item}}
                  <img
                    src="/static/image/device/delect_equment.png"
                    style="float:right;margin:16px;"
                    @click="delectBox(item)"
                  >
                </div>
              </div>
            </vue-scroll>
          </el-row>
          <!-- 第二步 -->
          <el-row
            :gutter="20"
            style="margin-top:30px!important;background:F8F8F8;"
            v-if="disc_current === 2"
          >
            <vue-scroll :ops="ops">
              <div
                style="width: 100%;display: inline-block;box-sizing: border-box;height:450px;padding:0 27px 30px"
              >
                <el-col
                  :site="tableSite"
                  :span="4"
                  v-for="(item,index) in tableSite"
                  :key="index"
                  style="width:20%;padding:0"
                >
                  <div class="grid-content" style="margin: 30px 13px 0px; ">
                    <el-button
                      type="info"
                      size="medium"
                      round
                      @click="click_disc_current(index)"
                      :class="disc_active === index ? 'btn-current':''"
                      style="width:156px;border: 1px solid #D9D9D9;background:#fff;color:#8891A2;white-space: nowrap;text-overflow: ellipsis;overflow:hidden;height: 36px;font-size: 14px;"
                    >{{item.name}}</el-button>
                  </div>
                </el-col>
              </div>
            </vue-scroll>
          </el-row>
          <div class="dialog-footer footer" v-if="disc_current !== 3">
            <el-button
              type="primary"
              class="btnClosed"
              @click="closeDisc"
            >{{disc_current === 2 ? "上一步" : '取消'}}</el-button>
            <el-button
              type="primary"
              @click="next"
              :disabled="can_next"
              class="btnSaved"
              :class="{btnAdd:!can_next,add:can_next}"
            >下一步</el-button>
          </div>
          <!-- 第三步 -->
          <el-row
            :gutter="20"
            style="margin:30px 0 0px 0;"
            v-if="disc_current === 3"
          >
            <img
              src="/static/image/device/b-red.png"
              alt
              style="margin: 20px auto;display: block;"
            >
            <p style="text-align: center;">已入库完成，3s后将自动关闭弹窗</p>
          </el-row>
        </div>
      </el-tabs>
    </template>
  </el-dialog>
</template>
<script>
import Config from "@/config";
import qs from "qs";
import { mapGetters } from "vuex";
export default {
  name: 'Newequment',
  props: ["messageflag"],
  data() {
    return {
      ops: {
        bar: {
          background: "#DDDEE0"
        }
      },
      // 入库分配弹框
      dialogTablesVisible: false,
      // 选择第二步点击添加颜色
      disc_active: null,
      disc_current: 1,
      set: {
        box_number: ""
      },
      show_one: true,
      arrbox: [], //分配盒子
      // 获取库房站点
      tableSite: [],
      boxDatas: [],
      isBoxLoading: false
    };
  },
  methods: {
    // 扫码搜索箱号
    boxs_list() {
      this.isBoxLoading = true
      let url = `${Config.DEVICE_MANAGE_URL}/inventory/queryCommon?devtype=${Config.objType.devtype}`;
      let params = {
        box_number: this.set.box_number ? this.set.box_number : undefined
      }
      this.$http.get(url,params).then(res =>{
        this.isBoxLoading = false
        if (!res.array.length) {
          this.$message("暂无");
          return;
        }

        var current_box = res.array.map(item => {
          return item;
        });
        var current_ownerId = res.array.map(item => {
          return item.current_owner_id;
        });
        if (current_ownerId.find(res => res !== 1)) {
          this.$message({message: `已入库,当前库位${current_box.find(res => res.current_owner).current_owner}`,type:'warning'})
          return
        }
        this.arrbox.push(this.set.box_number); //存储箱子
        this.show_one = false;
        this.set.box_number = "";
      }).catch(e =>{
        
      })
    },
    // 判断有没有箱号  以及重复
    search_box() {
      var a = 0;
      if (!this.arrbox.length) {
        this.boxs_list()
      } else {
        this.arrbox.forEach((item, i) => {
          if (item === this.set.box_number) {
            a++;
            this.set.box_number = "";
            this.$message({message: "箱号重复",type: "warning"});
          }
        });
        if (!a) {
          this.boxs_list()
        }
      }
    },
    // 分配扫码监听input框
    enterBox(value) {
      if(value === '') return
      this.search_box()
    },
   // 获取库房站点
    getsite() {
      const url = `${Config.DEVICE_MANAGE_URL}/storehouses/query_common?page=0&size=100&store_level=1&house_owner=${this.user.company}`;
      var params = {};
       if (this.district.districtType === 1) {
       params.country = '86';
      }else if (this.district.districtType === 2) {
        params.province = this.district.provinceCode;
      } else if(this.district.districtType === 3) {
        params.city = this.district.cityCode;
      }
      this.$http.get(url, params).then(res => {
        this.tableSite = res.array;
      });
    },
    // 扫码删除
    delectBox(value) {
      this.arrbox.map((item, i) => {
        if (item === value) {
          this.arrbox.splice(i, 1);
        }
      });
      this.$message({ type: "success", message: "删除成功!" });
    },
    // 颜色切换
    click_disc_current(index) {
      this.disc_active = index;
    },
    //imei分配装箱
    next() {
      // 点击下一步
      if (this.disc_current === 1) {
        this.disc_current = 2;
        this.getsite()
        this.show_one = false;
      } else {
        this.$confirm("确定下一步吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(value => {
            if (value) {
              // 整箱分配
              this.postbox();
              setTimeout(() => {
                this.dialogTablesVisible = false;
              }, 3000);
            }
            this.$message({
              type: "success",
              message: "入库成功!"
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消入库"
            });
          });
      }
    },
    // 整箱分配提交
    postbox() {
      this.arrbox.map(item => {
        this.boxDatas.push(item);
      });
      let url = `${
        Config.DEVICE_MANAGE_URL
      }/inventory/inboundByBoxsBatch`;
      this.$http
        .post(
          url,
          qs.stringify({
            devtype: Config.objType.devtype,
            boxs: this.boxDatas.toString(),
            current_owner: this.tableSite[this.disc_active].name,
            current_owner_id: this.tableSite[this.disc_active].id
          }),
          { "Content-Type": "application/x-www-form-urlencoded" }
        )
        .then(res => {
          this.disc_current = 3;
          this.boxDatas = [];
          this.$emit('change')
        });
    },
    closeDisc() {
      if (this.disc_current === 1) {
        this.dialogTablesVisible = false;
      } else if (this.disc_current === 2) {
        this.disc_current = 1;
      } else {
        this.dialogTablesVisible = false;
      }
    }
  },
  computed: {
    can_next() {
      if (this.disc_current === 1) {
        if (this.arrbox.filter(res => res).length) {
          return false;
        } else {
          return true;
        }
      }
      if (this.disc_current === 2) {
        if (this.disc_active === -1) {
          return true;
        } else {
          return false;
        }
      }
    },
    ...mapGetters("user", {
      district: "getDistrict",
      role: "getRole",
      user: "getUser"
    })
  },
  watch: {
    messageflag(data) {
      if (data) {
        this.dialogTablesVisible = data;
        this.set.box_number = "";
        this.arrbox = [];
        this.disc_active = -1;
        this.show_one = true;
        this.dialogTablesVisible = true;
        this.disc_current = 1;
        // 自动获取焦点
        this.$nextTick(() => {
          this.$refs.inputsbox.focus();
        });
        this.boxDatas = [];
      }
    },

    // 弹框关闭
    dialogTablesVisible(data) {
      if (!data) {
        // 子向父
        this.$emit("listenflag", false);
      }
    }
  }
};
</script>
